package com.zzk.lanouhn.myapplication1.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.squareup.picasso.Picasso;
import com.zzk.lanouhn.myapplication1.R;
import com.zzk.lanouhn.myapplication1.activity.ArticlesListDetailsActivity;
import com.zzk.lanouhn.myapplication1.activity.AttenetionDetailsActivity;
import com.zzk.lanouhn.myapplication1.activity.MessageArticleGuide;
import com.zzk.lanouhn.myapplication1.activity.NewestDetailsActivity;
import com.zzk.lanouhn.myapplication1.activity.RankDetailsActivity;
import com.zzk.lanouhn.myapplication1.adapters.MessageArticlesAdapter;
import com.zzk.lanouhn.myapplication1.intefaces.NewsItemCliclListener;
import com.zzk.lanouhn.myapplication1.modles.GuidePic;
import com.zzk.lanouhn.myapplication1.modles.MessageArticles;
import com.zzk.lanouhn.myapplication1.utils.HttpUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lanouhn on 16/9/1.
 */
public class MessageArticleFragment extends Fragment implements NewsItemCliclListener {

    private RadioButton btn_attenetion, btn_rank, btn_newest;
    private ImageView iv_guide;
    private XRecyclerView scrollRecyclerView;
    private GuidePic guidePic;
    private MessageArticlesAdapter adapter;
    private List<MessageArticles.DataBean.TopicBean> articles=new ArrayList<>();
    private List<MessageArticles.DataBean.TopicBean> tempArticles=new ArrayList<>();
    private int page = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_articles_message, null);
//        btn_attenetion= (RadioButton) view.findViewById(R.id.radio_attention_message);
//        btn_newest= (RadioButton) view.findViewById(R.id.radio_newest_message);
//        btn_rank= (RadioButton) view.findViewById(R.id.radio_rank_message);
//        iv_guide= (ImageView) view.findViewById(R.id.iv_guide_message);
        View view2 = LayoutInflater.from(getActivity()).inflate(R.layout.view_head_article_message, null);
        btn_attenetion = (RadioButton) view2.findViewById(R.id.radio_attention_message);
        btn_newest = (RadioButton) view2.findViewById(R.id.radio_newest_message);
        btn_rank = (RadioButton) view2.findViewById(R.id.radio_rank_message);
        iv_guide = (ImageView) view2.findViewById(R.id.iv_guide_message);
        scrollRecyclerView = (XRecyclerView) view.findViewById(R.id.recycler_articles_message);
        scrollRecyclerView.setFocusable(false);
        scrollRecyclerView.addHeaderView(view2);
        getDataFromWeb();
        initEvent();
        refresh();
        return view;
    }

    private void refresh() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        scrollRecyclerView.setLayoutManager(manager);
        //上拉加载的动画效果
        scrollRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        //下拉刷新的动画效果
        scrollRecyclerView.setArrowImageView(R.drawable.ic_loading_rotate);
        scrollRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            //下拉刷新
            @Override
            public void onRefresh() {
                page = 0;
                getDataFromWeb();
            }

            //上拉加载
            @Override
            public void onLoadMore() {
                page += 1;
                getDataFromWeb();
            }
        });

    }

    private void getDataFromWeb() {
        String guideImgUrl = "http://open4.bantangapp.com/community/post/article";
        String guideImgparam = "app_id=com.jzyd.BanTang" +
                "&client_id=bt_app_android" +
                "&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2560255" +
                "&oauth_token=4df22230db195bba652ef0e593881122&track_deviceid=866479023806507" +
                "&track_device_info=x600&channel_name=leshi" +
                "&app_installtime=1471853508" +
                "&app_versions=5.8.6&os_versions=5.0.2&screensize=1080&v=18";
        try {
            HttpUtils.doPostAsyn(guideImgUrl, guideImgparam, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson1 = new Gson();
                    guidePic = gson1.fromJson(result, GuidePic.class);
                    if (guidePic.getData().getInsert_element().size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        String s = String.valueOf(page);
        String articlesUrl = "http://open4.bantangapp.com/topics/topic/listByUsers";
        String articlesParams = "app_id=com.jzyd.BanTang" +
                "&client_id=bt_app_android" +
                "&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d" +
                "&track_user_id=2560255&oauth_token=4df22230db195bba652ef0e593881122" +
                "&track_deviceid=866479023806507&track_device_info=x600" +
                "&channel_name=leshi&app_installtime=1471853508&app_versions=5.8.6&os_versions=5.0.2" +
                "&screensize=1080&v=18&page=" + s + "&pagesize=20&sort_type=1";

        try {
            HttpUtils.doPostAsyn(articlesUrl, articlesParams, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson2 = new Gson();
                    tempArticles = gson2.fromJson(result, MessageArticles.class).getData().getTopic();
                    if (tempArticles.size() > 0) {
                        handler.sendEmptyMessage(2);

                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    Picasso.with(getActivity()).load(guidePic.getData().getInsert_element().get(0).getPhoto()).into(iv_guide);
                    break;
                case 2:

                    if (page == 0) {
                        articles.clear();
                        articles.addAll(tempArticles);
                        adapter = new MessageArticlesAdapter(getActivity(), articles);
                        scrollRecyclerView.setAdapter(adapter);
                        adapter.setScrollRecyclerViewAdapter(MessageArticleFragment.this);
                        scrollRecyclerView.refreshComplete();
                        tempArticles.clear();
                    } else {
                        articles.addAll(tempArticles);
                        adapter.notifyDataSetChanged();
                        scrollRecyclerView.loadMoreComplete();
                        tempArticles.clear();
                    }
                    break;
                default:

                    break;
            }
        }
    };

    private void initEvent() {
        btn_attenetion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AttenetionDetailsActivity.class);
                startActivity(intent);
            }
        });
        btn_newest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), NewestDetailsActivity.class);
                startActivity(intent);
            }
        });
        btn_rank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), RankDetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("排行榜", guidePic.getData().getRank_url());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        iv_guide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), MessageArticleGuide.class);
                intent.putExtra("guideUrl","http://m.bantangapp.com/guide2.html");
                startActivity(intent);
            }
        });
    }

    @Override
    public void onItemClick(int position) {
        Intent intent = new Intent(getActivity(), ArticlesListDetailsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("内容", articles.get(position-2).getId());
        intent.putExtras(bundle);
        startActivity(intent);
    }
}
